<template>
  <div class="question-container">
    <!-- 搜索与筛选区域 -->
    <el-row :gutter="15" style="margin-bottom: 15px;">
      <el-col :span="6">
        <el-input 
          v-model="searchKeyword" 
          placeholder="输入关键词搜索问题"
          @input="applyFilter"
          clearable
        >
        </el-input>
      </el-col>
      <!-- 面试难度筛选 -->
      <el-col :span="4">
        <el-select v-model="difficultyFilter" placeholder="选择难度" clearable @change="applyFilter">
          <el-option
            v-for="(label, value) in difficultyMap"
            :key="value"
            :label="label"
            :value="Number(value)"
          />
        </el-select>
      </el-col>

      <!-- 领域类型筛选 -->
      <el-col :span="4">
        <el-select v-model="fieldTypeFilter" placeholder="选择领域" clearable @change="applyFilter">
          <el-option
            v-for="(label, value) in fieldTypeMap"
            :key="value"
            :label="label"
            :value="Number(value)"
          />
        </el-select>
      </el-col>

      <!-- 面试场景筛选 -->
      <el-col :span="4">
        <el-select v-model="interviewSceneFilter" placeholder="选择场景" clearable @change="applyFilter">
          <el-option
            v-for="(label, value) in interviewSceneMap"
            :key="value"
            :label="label"
            :value="Number(value)"
          />
        </el-select>
      </el-col>

      <!-- 可选：重置按钮 -->
      <el-col :span="1">
        <el-button @click="resetFilters">重置</el-button>
      </el-col>

      <!-- 新增按钮 -->
      <el-col :span="3">
        <el-button type="primary" @click="showAddDialog">+ 新增问题</el-button>
      </el-col>
    </el-row>

    <!-- 表格展示 -->
    <el-table :data="paginatedQuestions" style="width: 100%; margin-top: 10px; border-radius: 8px; overflow: hidden;"
      :row-style="{ backgroundColor: '#f9f9f9' }"
    >
      <el-table-column label="序号" min-width="55" type="index" align="center" class-name="custom-index-column" />

      <el-table-column prop="questionContent" label="问题内容" show-overflow-tooltip />
      <el-table-column prop="referenceAnswer" label="参考答案" show-overflow-tooltip />

      <el-table-column prop="difficulty" label="难度" width="80" style=" margin-top: 10px; border-radius: 8px; overflow: hidden;"
      :row-style="{ backgroundColor: '#f9f9f9' }">
        <template #default="{ row }">
          {{ difficultyMap[row.difficulty] }}
        </template>
      </el-table-column>

      <el-table-column prop="interviewScene" label="面试场景" width="100">
        <template #default="{ row }">
          {{ interviewSceneMap[row.interviewScene] }}
        </template>
      </el-table-column>

      <el-table-column prop="fieldType" label="领域类型" width="100">
        <template #default="{ row }">
          {{ fieldTypeMap[row.fieldType] }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button size="small" type="primary" @click="editQuestion(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteQuestion(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
  <el-row justify="end">
  <el-col :span="6" style="display: flex; justify-content: flex-end;">
    <el-pagination
      layout="prev, pager, next"
      :total="totalQuestions"
      :page-size="pageSize"
      :current-page="currentPage"
      @current-change="handlePageChange"
    />
  </el-col>
</el-row>
    
<!-- 新增/编辑对话框 -->
 <el-dialog 
    v-model="dialogVisible" 
    :title="isEditing ? '编辑问题' : '新增问题'"
    width="800px"
    class="custom-dialog"
  >
    <el-form :model="currentQuestion" label-width="100px" class="dialog-form">
      
      <!-- 面试场景 -->
      <el-form-item label="面试场景">
        <el-select 
          v-model="currentQuestion.interviewScene" 
          placeholder="请选择面试场景" 
          class="form-select"
          style="width: 100%"
        >
          <el-option
            v-for="(label, value) in interviewSceneMap"
            :key="value"
            :label="label"
            :value="Number(value)"
          />
        </el-select>
      </el-form-item>
      
      <!-- 领域类型 -->
      <el-form-item label="领域类型">
        <el-select 
          v-model="currentQuestion.fieldType" 
          placeholder="请选择领域类型" 
          class="form-select"
          style="width: 100%"
        >
          <el-option
            v-for="(label, value) in fieldTypeMap"
            :key="value"
            :label="label"
            :value="Number(value)"
          />
        </el-select>
      </el-form-item>
<!-- 难度 -->
      <el-form-item label="难度">
        <el-select 
          v-model="currentQuestion.difficulty" 
          placeholder="请选择难度" 
          class="form-select"
          style="width: 100%"
        >
          <el-option
            v-for="(label, value) in difficultyMap"
            :key="value"
            :label="label"
            :value="Number(value)"
          />
        </el-select>
      </el-form-item>
      
      <!-- 问题内容 -->
      <el-form-item label="问题内容">
        <el-input 
          v-model="currentQuestion.questionContent" 
          type="textarea" 
          :rows="3" 
          placeholder="请输入问题内容"
          class="form-input"
        />
      </el-form-item>
      
      <!-- 参考答案 -->
      <el-form-item label="参考答案">
        <el-input 
          v-model="currentQuestion.referenceAnswer" 
          type="textarea" 
          :rows="5" 
          placeholder="请输入参考答案"
          class="form-input"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false" class="cancel-btn">取消</el-button>
        <el-button type="primary" @click="submitQuestion" class="submit-btn">
          {{ isEditing ? '更新' : '提交' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';

// API 地址
const questionApi = 'http://localhost:8080/question';

// 数据状态
const questions = ref([]);             // 所有问题
const filteredQuestions = ref([]);     // 过滤后的问题
const currentPage = ref(1);
const pageSize = ref(10);
const totalQuestions = ref(0);

// 弹窗相关
const dialogVisible = ref(false);
const isEditing = ref(false);
const currentQuestion = ref({
  id: null,
  questionContent: '',
  referenceAnswer: '',
  difficulty: 1,
  interviewScene: 1,
  fieldType: 1
});

// 查询条件
const searchKeyword = ref('');               // 关键词搜索
const difficultyFilter = ref(null);          // 难度筛选
const fieldTypeFilter = ref(null);           // 领域筛选
const interviewSceneFilter = ref(null);      // 场景筛选

// 字段映射（注意你这里用的是 0-based 索引）
const difficultyMap = {
  0: '简单',
  1: '中等',
  2: '困难'
};
const interviewSceneMap = {
  0: '技术岗',
  1: '运维测试岗',
  2: '产品岗'
};
const fieldTypeMap = {
  0: '人工智能',
  1: '大数据',
  2: '物联网',
  3: '智能系统'
};

onMounted(() => {
  fetchQuestions();
});

// 获取问题列表
const fetchQuestions = async () => {
  try {
    const response = await axios.get(`${questionApi}/all`);
    if (response.data.code === 200) {
      questions.value = response.data.data || [];
      applyFilter(); // 应用过滤
    } else {
      throw new Error(response.data.msg || '获取数据失败');
    }
  } catch (error) {
    ElMessage.error('获取问题列表失败: ' + error.message);
  }
};

// 多条件过滤逻辑
const applyFilter = () => {
  let result = [...questions.value];

  // 按关键词过滤
  const keyword = searchKeyword.value?.toLowerCase();
  if (keyword) {
    result = result.filter(q =>
      q.questionContent?.toLowerCase().includes(keyword)
    );
  }

  // 按难度过滤
  if (difficultyFilter.value !== null && difficultyFilter.value !== '') {
    result = result.filter(q => q.difficulty === difficultyFilter.value);
  }

  // 按领域过滤
  if (fieldTypeFilter.value !== null && fieldTypeFilter.value !== '') {
    result = result.filter(q => q.fieldType === fieldTypeFilter.value);
  }

  // 按面试场景过滤
  if (interviewSceneFilter.value !== null && interviewSceneFilter.value !== '') {
    result = result.filter(q => q.interviewScene === interviewSceneFilter.value);
  }

  // 更新分页数据
  filteredQuestions.value = result;
  totalQuestions.value = result.length;
  currentPage.value = 1;
};

// 重置所有筛选条件
const resetFilters = () => {
  searchKeyword.value = '';
  difficultyFilter.value = null;
  fieldTypeFilter.value = null;
  interviewSceneFilter.value = null;
  applyFilter();
};

// 分页计算
const paginatedQuestions = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredQuestions.value.slice(start, end);
});

// 页面切换
const handlePageChange = (page) => {
  currentPage.value = page;
};

// 显示新增弹窗
const showAddDialog = () => {
  isEditing.value = false;
  currentQuestion.value = {
    questionContent: '',
    referenceAnswer: '',
    difficulty: 1,
    interviewScene: 1,
    fieldType: 1
  };
  dialogVisible.value = true;
};

// 编辑问题
const editQuestion = (row) => {
  isEditing.value = true;
  currentQuestion.value = { ...row };
  dialogVisible.value = true;
};

// 提交新增或更新
const submitQuestion = async () => {
  try {
    if (isEditing.value) {
      await axios.put(`${questionApi}/update`, currentQuestion.value);
      ElMessage.success('更新成功');
    } else {
      await axios.post(`${questionApi}/add`, currentQuestion.value);
      ElMessage.success('新增成功');
    }
    dialogVisible.value = false;
    fetchQuestions();
  } catch (error) {
    ElMessage.error('操作失败: ' + error.message);
  }
};

// 删除问题
const deleteQuestion = async (id) => {
  ElMessageBox.confirm('确认删除该问题？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await axios.delete(`${questionApi}/delete/${id}`);
      ElMessage.success('删除成功');
      fetchQuestions(); // 刷新列表
    } catch (error) {
      ElMessage.error('删除失败: ' + error.message);
    }
  }).catch(() => {});
};
</script>
<style scoped>
/* 对话框整体样式 */
.custom-dialog {
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
}

/* 标题样式 */
:deep(.el-dialog__header) {
  padding: 24px 24px 16px;
  margin: 0;
  border-bottom: 1px solid #f0f0f0;
  background: linear-gradient(to right, #f8fafc, #ffffff);
  border-radius: 12px 12px 0 0;
}

:deep(.el-dialog__title) {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  display: flex;
  align-items: center;
}

:deep(.el-dialog__title)::before {
  content: "";
  display: inline-block;
  width: 4px;
  height: 18px;
  background: linear-gradient(to bottom, #409eff, #66b1ff);
  margin-right: 12px;
  border-radius: 2px;
}

/* 表单区域样式 */
.dialog-form {
  padding: 16px 0px 8px;
  text-align: left;
}

/* 表单标签样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
  padding-right: 12px;
}

/* 输入框样式 */
.form-input :deep(.el-textarea__inner) {
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s;
  padding: 12px 16px;
  font-size: 14px;
  line-height: 1.5;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05);
}

.form-input :deep(.el-textarea__inner):focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2), 
              inset 0 1px 3px rgba(0, 0, 0, 0.05);
}

/* 选择框区域样式 */
.form-select :deep(.el-input__inner) {
  border-radius: 8px;
  height: 40px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s;
}

.form-select :deep(.el-input__inner):focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 底部按钮区域 */
.dialog-footer {
  padding: 20px 32px;
  text-align: right;
  border-top: 1px solid #f0f0f0;
  background-color: #f9fafc;
  border-radius: 0 0 12px 12px;
}

.cancel-btn {
  border-radius: 8px;
  padding: 10px 24px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s;
  color: #606266;
}

.cancel-btn:hover {
  color: #409eff;
  border-color: #c6e2ff;
  background-color: #ecf5ff;
  transform: translateY(-1px);
}

.submit-btn {
  border-radius: 8px;
  padding: 10px 24px;
  background: linear-gradient(to right, #409eff, #66b1ff);
  border: none;
  transition: all 0.3s;
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.3);
}

.submit-btn:hover {
  background: linear-gradient(to right, #66b1ff, #409eff);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
}

/* 表单行间距调整 */
.el-row {
  margin-bottom: 16px;
}

/* 选择框标签样式 */
.el-form-item__label {
  font-weight: 500;
  color: #606266;
}
</style>